#include <your_servlet.h>
#include <http_conn.h>
#include <DAO.h>
#define PARSE_OVER 0
#define PARSE_MORE 1
#define PARSE_FAIL 2
string errorss("you are wrong!!!");
oal_uint8* login_html = "login.html";
oal_uint8* sign_html  = "flv.html";
oal_uint8* error_html = "signerror.html";
oal_bool get_file_content(string filepath,oal_uint8 **p1 , oal_uint32 *length)
{
	FILE* fp; 
	oal_uint8 *p;
	fp = fopen(filepath.c_str(),"rb");// localfile文件名  
	if(fp == oal_ptr_null)
	{
		oal_print("the file is not exsit\n");
		//http_obj->write(errorss);
		//oal_print("sendok\n");
		return false;
	}	      
	fseek(fp,0L,SEEK_END); /* 定位到文件末尾 */  
	oal_uint32 flen = ftell(fp); /* 得到文件大小 */  
	//oal_print("the file len is [%u]\n",flen);
	p = (oal_uint8 *)malloc(flen + 1); /* 根据文件大小动态分配内存空间 */  
	if(p==NULL)  
	{  
		fclose(fp);  
		oal_print("the file is not exsit\n");
		//http_obj->write(errorss);
		//oal_print("sendok\n");
		return false;
	}  
	fseek(fp,0L,SEEK_SET); /* 定位到文件开头 */  
	fread(p,1,flen,fp); /* 一次性读取全部文件内容 */  
	fclose(fp);
/*
函数名: fread
功  能: 从一个流中读数据
用  法: int fread(void *ptr, int size, int nitems, FILE *stream);
参  数：用于接收数据的地址（ptr） 
        单个元素的大小（size） 
        元素个数（nitems）
        提供数据的文件指针（stream）
返回值：成功读取的元素个数
程序例:
*/
	p[flen]=0; /* 字符串结束标志 */ 
	*length = flen;
	*p1 = p;
	return true;  
}
oal_uint32 parse_one_xml(unordered_map<string,string> &data_map,oal_uint8 *data ,oal_uint32 datalen)
{
	oal_uint32 proc_len = 0;
	string key;
	string value;
	oal_uint8 *temp = data;
	oal_uint8 *str = temp;
	if(*temp == '\r'&& *(temp + 1) == '\n')
	{
		return 2;
	}
	if(*temp == '\n')
	{
		return 1;
	}
	// str = strpbrk(temp,':');
	// if(str == oal_ptr_null)
	// {
	// 	oal_uint8 * cur_data = temp;
	// 	oal_uint32 temp_len = 0;
	// 	while(temp_len < datalen)
	// 	{
	// 		if(*cur_data == '\r' || *cur_data == '\n')
	// 		{
	// 			return temp_len;
	// 		}
	// 		temp_len++;
	// 		cur_data += temp_len;
	// 	}
	// 	return temp_len;
	// }
	oal_uint32 str_len = 0;
	oal_bool   exit_normal = false;
	while(str_len <= datalen)
	{
		if(*str == '=')
		{
			exit_normal = true;
			break;
		}
		str_len ++;
		str ++;
	}
	if(!exit_normal)
	{
		return str_len;
	}
	proc_len += str_len;
	key.append(temp,str_len);
	temp = str + 1;
	str++;
	proc_len ++;
	if(proc_len >= datalen)
	{
		return proc_len;
	}
	str_len = 0; 
	while(proc_len <= datalen)
	{
		if(*str == '&')
		{
			value.append(temp,str_len);
			data_map.insert(pair<string,string>(key,value));
			oal_print("post 0  key [%s] value [%s]\n",key.c_str(),value.c_str());
			return proc_len + 1;//+1 跳过&
		}
		str_len ++;
		proc_len ++;
		str ++;
	}
	value.append(temp,str_len - 1);
	oal_print("post 1  key [%s] value [%s]\n",key.c_str(),value.c_str());
	data_map.insert(pair<string,string>(key,value));
	return proc_len ;
}
oal_bool parse_xml(unordered_map<string,string> &data_map,oal_uint8 *data ,oal_uint32 data_len)
{
	oal_uint8 *temp_data = data;
	oal_uint32  proc_len = 0;
	while(1)
	{
		oal_uint32 temp_len = 0;
		temp_len = parse_one_xml(data_map,temp_data,data_len - proc_len);
		proc_len += temp_len;
		temp_data += temp_len;
		if(proc_len >= data_len)
		{
			break;
		}
	}
	oal_print("data [%s] proc_len is [%u] datalen [%u]\n",data,proc_len,data_len);
	return true;
}
oal_void send_cliet(oal_uint8 *data ,oal_uint32 length , string &content_type ,http_conn* http_obj)
{
	if(length > 3800)
	{
		oal_print("xxxxxxxxx  ext/html\n");
		http_obj->write_byte(data,length,content_type);
		//http_obj->write_byte(data,length,"text/html");
		//oal_print("xxxxxxxxx  application/octet-stream\n", p);
		//http_obj->write_byte(data,length,"application/octet-stream");
	}
	else
	{
		string content(data);
		oal_print("ooooooooooo \n");
		http_obj->write(content);
	}
}
oal_int32 test_servlet(void* obj)
{
	// char *test_html2222 = "resource/beauty.mp4";
	// //char *test_html2222 = "resource/login.jpg";
	// char *test_html = test_html1111;
	// http_conn* http_obj = (http_conn*)obj; 
	// if(http_obj->getUrl() == "/resource/beauty.mp4")
	// {
	// 	oal_print("get image\n");
	// 	test_html = test_html2222;
	// }
	string content_type;
	oal_print("servlet in\n");
	http_conn* http_obj = (http_conn*)obj; 
	string urls   = http_obj->getUrl();
	string method = http_obj->getMethod();
	if(method == "GET")
	{ 
		if(urls.size()==0)
		{
			urls.append(sign_html);
			content_type.append("text/html");
		}
		else
		{
			content_type.append("application/octet-stream");
		}
		//oal_print("the url is : [%s]\n",urls.c_str());
		oal_uint8 *p;
		oal_uint32 flen;
		if(!get_file_content(urls,&p,&flen))
		{
			http_obj->write(errorss);
			return 0;
		}
		send_cliet(p,flen,content_type,http_obj);
		free(p);
	}
	else if(method == "POST")
	{
		oal_uint8 index = 0;
		if(urls == "login")
		{
			index = 1;
		}
		unordered_map<string,string> data_map;
		oal_uint8 *data = oal_ptr_null;
		string account;
		string password;
		string real_pwd;
		string output_file;
		oal_uint8 *p;
		oal_uint32 flen;
		switch(index)
		{
			case 1:
				
				data = http_obj->get_data();
				if(data != oal_ptr_null)
				{
					parse_xml(data_map,data,http_obj->data_len);
				}
				
				if(data_map.find("account") != data_map.end())
				{
					account = data_map["account"];
				}
				if(data_map.find("password") != data_map.end())
				{
					password = data_map["password"];
				}
				oal_print("servlet  account [%s] password [%s]\n",account.c_str(),password.c_str());
				real_pwd = query_sql_password(account);
				//oal_print("12324\n");
				if(real_pwd == password)
				{
					output_file.append(login_html);
				}
				else
				{
					output_file.append(error_html);
				}
				if(!get_file_content(output_file,&p,&flen))
				{
					http_obj->write(errorss);
					return 0;
				}
				//oal_print("xxxxx\n");
				content_type.append("text/html");
				send_cliet(p,flen,content_type,http_obj);
				free(p);
				break;
			default:
				http_obj->write(errorss);
				break;
		}
	}
   // oal_print("the image len [%u]\n",flen);
	// oal_uint8* html_data;
	// oal_uint32 text_len ;
	// oal_uint32  file_fd = open(test_html ,O_RDWR);

	// if(file_fd<0)
	// {
	// 	html_data = "filed";
	// 	oal_print("cannot open the login.html\n");
	// }
	// else
	// {
	// 	text_len = read(file_fd,);
	// }
	//oal_print("the context :\n %s\n", p);
	return 0;
	
}